/**
 * 适配器模式：
 * 案例：axios 既可以在浏览器下用，也可以在node环境下，在不同的环境下，使用的统一的，在核心中，实际上使用了适配器模式，将http模块，xhr的实现封装在底层的逻辑中，暴露统一的api
 */

 //场景：将项目中使用ajax方式的代码改为使用fetch，添加适配器无缝转换

 // fetch方式
export default class HttpUtils {
    static get(url, data) {
        return new Promise((resolve, reject) => {
            fetch(url, {
                method: 'GET',
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                resolve(result)
            })
            .catch(error => {
                reject(error)
            })
        })
    }

    static post(url, data) {
        return new Promise((resolve, reject) => {
            fetch(url, {
                method: 'POSt',
                headers: {
                    Accept: 'application/json',
                    'Content-Type':'application/x-www-form-urlencoded'
                },
                body: this.changeData(data)
            })
            .then(response => response.json())
            .then(result => {
                resolve(result)
            })
            .catch(error => {
                reject(error)
            })
        })
    }

    static changeData(obj) {
        var prop, str = '';
        var i = 0 ;
        for (prop in obj){
            if (!prop) {
                return
            }
            if (i = 0) {
                str += prop +'='+obj[prop]
            }else {
                str += '&' + prop +'=' + obj[prop]
            }
            i++
        }
        return str;
    }
}

// ajax方式
function Ajax(type, url, data, success, failed) {
    var xhr = null;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }else {
        xhr = new ActiveXObject('Microsoft XMLHTTP')
    }

    var type = type.toUpperCase();

    if (type === 'GET') {
        if (data) {
            xhr.open('GET', url + '?' + data, true)
        }
        xhr.send()
    }else if (type === 'POST') {
        if (data) {
            xhr.open('POST', url, true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
            xhr.send(data)
        }
    }
    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4) {
            if (xhr.status === 200) {
                success(xhr.responseText)
            }else {
                if (failed) {
                    failed(xhr.status)
                }
            }
        }
    }
}

// 适配器：将ajax方式无缝改为fetch
async function AjaxAdapter(type, url, data, success, failed ) {
    const _type = type.toUpperCase();
    let result; 
    try {
        if (_type === 'GET') {
            result = await HttpUtils.get(url, data) || {}
        }else if (_type === 'POST') {
            result = await HttpUtils.post(url, data) || {}
        }
        result.code === 1 && success ? success(result) :failed(result.status);
    }catch(error) {
        if (failed) {
            failed(error)
        }
    }
}

const Ajax = function(type, url, data, success, failed) {
    AjaxAdapter(type, url, data, success, failed);
}


// 区分node环境，浏览器环境
if (typeof process !=='undefined' & Object.prototype.toString.call(process) === '[object process]') {
    // node 环境
}else if (typeof XMLHttpRequest !== 'undefined') {
 }